/*
 * @Autor: dingxiaolin
 * @Date: 2021-01-18 19:14:28
 * @LastEditors: dingxiaolin
 * @LastEditTime: 2021-01-25 20:19:24
 */
import { readFileSync, writeFileSync, existsSync } from 'fs';
import { resolve } from 'path';
import prettier from 'prettier';
import fetch from 'node-fetch';
import { ApiConfig } from './swagger';
(async () => {
    const sourceUrl = process.argv[2];
    let buff = '';
    if (sourceUrl.includes('http://') || sourceUrl.includes('https://')) {
        buff = await fetch(sourceUrl).then((r) => r.text());
    } else {
        buff = readFileSync(sourceUrl).toString();
    }
    const output = process.argv[3] || 'output';
    const source: ApiConfig = JSON.parse(buff);
    const apis = Object.keys(source.paths);
    var content = [
        `import { Post, Get, Patch, Put, Delete, Download, ax } from './http'`,
    ];
    apis.map((url) => {
        const api = source.paths[url];
        let arr = url.split('/');
        var fn = arr.pop();
        var namespace = '';
        ['get', 'post', 'put', 'delete'].map((method) => {
            const { summary, parameters, responses, tags } = api[method] || {};
            if (!summary) return;
            if (url.includes('{')) {
                fn = arr[arr.length - 1];
                url = url.replace('{', '${');
                var value = url.slice(url.indexOf('{') + 1, url.indexOf('}'));
                content = content.concat([
                    `/**`,
                    `* ${summary}`,
                    `*/`,
                    `export var ${fn} = ${value} => {
                return ${method.charAt(0).toUpperCase() +
                    method.slice(1)}(\`${url}\`, {})
            }`,
                ]);
            } else {
                if (parameters && parameters.length == 0) {
                    var obj = '{}';
                } else {
                    obj = 'obj';
                }
                content = content.concat([
                    `/**`,
                    `* ${summary}`,
                    `*/`,
                    `export var ${fn} = obj => {
                return ${method.charAt(0).toUpperCase() +
                    method.slice(1)}(\`${url}\`, ${obj})
            }`,
                ]);
            }

            writeFileSync(
                resolve(output, 'api11.ts'),
                prettier.format(content.join('\n'), {
                    parser: 'typescript',
                    tabWidth: 4,
                }),
            );
        });
    });
})();
